const app = getApp()

const { extend, Field, Stepper, Toast, Actionsheet } = require('../../zanui/index')
import { formatTime, obj2Form } from '../../utils/util.js'

Page(extend({}, Field, Toast, Stepper, Actionsheet, {

  /**
   * 页面的初始数据
   */
  data: {
    payTypes: [],//支付方式选择bindImgLongTab
    supportServiceFacilities: [],//支持服务、设备类型
    storeDetailAddress: '',//详细地址
    storeNameChinese: '',
    storeNameEnglish: '',
    storeIntro: '',
    storeAddressChinese: '',
    storeAddressEnglish: '',
    storeLongitude: '',
    storeLatitude: '',
    storeBelongProvince: '',
    storeBelongRegion: '',
    storePostalCode: '',
    storeBuildingDescription: '',
    storeBelongGroup: '',
    storeCategory: '',
    needReserve: 0,
    reservePersonName: '',
    reservePhone: '',
    reserveFaxNumber: '',
    receptionPhone: '',
    receptionFaxNumber: '',
    businessStartTime: '9:00',
    businessEndTime: '20:00',
    consumptionPerPerson: 0.0,
    storeOpeningDate: '1960-01-01',
    latelyDecorationDate: '1960-01-01',
    decorationType: 0,
    accessoryBusStation: '',
    accessoryBusinessZone: '',
    accessoryParkingLot: '',
    supportPayType: [],
    supportServiceFacility: [],
    otherSupplement: '',
    storeImages: [],
    uploadDisabled: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '餐饮店铺信息'
    })

    // 存在id，设置默认数据
    if (options.id) {
      this.getCatering(options.id)
    }
    //支付方式
    wx.request({
      url: 'https://qdndc.ideatower.cn/v1/payType',
      success: (res) => {
        if (res.data.data.length > 0) {
          const data = res.data.data
          if (this.data.supportPayType.length > 0) {
            data.forEach(item => {
              if (this.data.supportPayType.findIndex(o => o == item.id) > -1) {
                item.checked = true
              } else {
                item.checked = false
              }
            })
          }
          this.setData({
            payTypes: res.data.data
          });
        } else {
          this.showZanToast('暂无支付方式信息');
        }
      },
      fail: (err) => {
        this.showZanToast('获取支付方式失败');
      }
    });

    //支持服务类型
    const _self = this
    wx.request({
      url: 'https://qdndc.ideatower.cn/v1/catering/serviceFacility',
      success: (res) => {
        if (res.data.data.length > 0) {
          const tmp = res.data.data
          if (_self.data.supportServiceFacility.length > 0) {
            tmp.forEach(item => {
              if (_self.data.supportServiceFacility.findIndex(o => o == item.id) > -1) {
                item.checked = true
              } else {
                item.checked = false
              }
            })
          }
          _self.setData({
            supportServiceFacilities: tmp
          })
        } else {
          _self.showZanToast('暂无服务类型信息');
        }
      },
      fail: (err) => {
        this.showZanToast('获取服务类型失败');
      }
    })
  },

  /**
   * 提交数据
   */
  formSubmit: function (event) {
    //追加单选钮数据
    const formData = event.detail.value
    formData.needReserve = 0
    if (this.data.needReserve != null){
      formData.needReserve = this.data.needReserve
    }
    formData.decorationType = this.data.decorationType
    formData.supportPayType = this.data.supportPayType.join(';')
    formData.supportServiceFacility = this.data.supportServiceFacility.join(';')
    
    const tmpImgs = []
    this.data.storeImages.forEach(item => {
      if (item.uploadStatus == 1 && item.downloadPath) {
        tmpImgs.push(item.downloadPath)
      }
    })
    formData.storeImages = tmpImgs.join(';')

    if (formData.needReserve == 1 && (formData.reservePersonName == '' || formData.reservePhone == '')) {
      this.showZanToast('请填写完整的预定信息')
      return
    }
    for (let key in formData) {
      if (key != 'storeNameEnglish' && key != 'storeAddressEnglish' && key != 'receptionFaxNumber' && key != 'storeBuildingDescription' && key != 'storeBelongGroup' &&
        key != 'accessoryBusStation' && key != 'accessoryBusinessZone' && 
        (key != 'reservePersonName' && key != 'reservePhone' && key != 'reserveFaxNumber') &&
        key != 'decorationType' && formData[key] == '' && formData[key] != 0) {
        this.showZanToast('数据不能为空')
        return
      }
    }
    this.setData({
      submitDisabled: true
    })
    wx.showLoading({
      title: '加载中',
    });

    const _self = this
    let requestMethod = 'POST'
    let requestUrl = 'https://qdndc.ideatower.cn/v1/catering'
    if (this.data.id) {
      // 更新
      formData.updateBy = app.globalData.userInfo.openid;
      requestMethod = 'PUT'
      requestUrl = 'https://qdndc.ideatower.cn/v1/catering/' + this.data.id
    } else {
      // 添加
      formData.areaId = app.globalData.areaInfo.id;
      formData.createBy = app.globalData.userInfo.openid;
    }
    wx.request({
      url: requestUrl,
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: obj2Form(formData),
      method: requestMethod,
      success: function (res) {
        if (res.statusCode != 200) {
          _self.showZanToast('请求接口失败')
          return
        }
        if (res.data.code != '000000') {
          _self.showZanToast(res.data.message)
          return
        }
        wx.navigateTo({
          url: `../cateringDishes/cateringDishes?id=${res.data.data.id}&storeName=${res.data.data.storeNameChinese}`
        })
      },
      fail: function () {
        _self.showZanToast('网络错误')
      },
      complete: function () {
        _self.setData({
          submitDisabled: false
        })
        wx.hideLoading()
      }
    })
  },
  /**
   *支持服务及设施 
   */
  supportServiceFacilityCheckboxChange: function (event) {
    this.setData({
      supportServiceFacility: event.detail.value
    });
  },
  /**
   * 选择支付方式点击事件
   */
  payTypeCheckboxChange: function (event) {
    this.setData({
      supportPayType: event.detail.value
    });
  },
  /**
   * 日期、时间选择事件绑定
   */
  bindPickerChange: function (e) {
    this.setData({
      [`${e.currentTarget.id}`]: e.detail.value
    })
  },
  /**
   * 单选钮事件
   */
  needReserveRadioChange: function (e) {
    this.setData({
      needReserve: e.detail.value
    });
  },
  decorationTypeChange: function (e) {
    this.setData({
      decorationType: e.detail.value
    });
  },
  /**
   * 定位
   */
  bindSelectMap: function () {
    const _self = this
    wx.chooseLocation({
      success: (data) => {
        _self.setData({
          storeLatitude: data.latitude,
          storeLongitude: data.longitude,
          storeAddressChinese: data.address
        });
        //根据经纬度获取别的信息
        wx.request({
          url: 'https://api.map.baidu.com/geocoder/v2/?ak=PgtdDGnL4iGj083t7b7d0fAO&callback=renderReverse&output=json&pois=1&location=' + _self.data.storeLatitude + ',' + _self.data.storeLongitude,
          success: (res) => {
            const currData = JSON.parse(res.data.substring(res.data.indexOf("(") + 1, res.data.lastIndexOf(")")));
            _self.setData({
              storeBelongProvince: currData.result.addressComponent.province,
              storeBelongRegion: currData.result.addressComponent.district
            });
            //获取邮编
            wx.request({
              url: 'https://qdndc.ideatower.cn/v1/postcode/' + currData.result.addressComponent.province + currData.result.addressComponent.district,
              success: (res) => {
                if (res.data.data.rs.length > 0) {
                  _self.setData({
                    storePostalCode: res.data.data.rs[0].POSTCODE
                  });
                } else {
                  this.showZanToast('获取邮编失败，您可以选择手动输入');
                }
              },
              fail: (err) => {

              }
            })
          },
          fail: (err) => {
            this.showZanToast('加载省份，行政区失败！');
          }
        })
      }
    })
  },
  getCatering: function (id) {
    const _self = this
    wx.request({
      url: 'https://qdndc.ideatower.cn/v1/catering',
      data: {
        id: id
      },
      success: (res) => {
        if (res.statusCode == 200 && res.data.code == '000000') {
          const data = res.data.data[0]
          if (data.supportPayType) {
            data.supportPayType = data.supportPayType.split(';')
            if (_self.data.payTypes.length > 0) {
              _self.data.payTypes.forEach(item => {
                if (data.supportPayType.findIndex(o => o == item.id) > -1) {
                  item.checked = true
                } else {
                  item.checked = false
                }
              })
              _self.setData({
                payTypes: _self.data.payTypes
              })
            }
          }
          if (data.supportServiceFacility) {
            data.supportServiceFacility = data.supportServiceFacility.split(';')
            if (_self.data.supportServiceFacilities.length > 0) {
              _self.data.supportServiceFacilities.forEach(item => {
                if (data.supportServiceFacility.findIndex(o => o == item.id) > -1) {
                  item.checked = true
                } else {
                  item.checked = false
                }
              })
              _self.setData({
                supportServiceFacilities: _self.data.supportServiceFacilities
              })
            }
          }
          if (data.storeImages) {
            const tmp = []
            data.storeImages.split(';').forEach((item, index) => {
              tmp.push({
                id: new Date().getTime() + '-' + index,
                src: item,
                downloadPath: item,
                uploadStatus: 1
              })
            })
            data.storeImages = tmp
          }
          _self.setData(data)
        } else {
          this.showZanToast('获取餐饮数据失败，请返回重新获取')
        }
      },
      fail: (err) => {
        this.showZanToast('获取餐饮数据失败，请返回重新获取')
      }
    })
  },
  selectImgs(e) {
    const _self = this
    wx.chooseImage({
      count: 12,
      sizeType: ['original'],
      sourceType: ['album'],
      success: function (res) {
        let tmp = _self.data.storeImages
        res.tempFilePaths.forEach((path, index) => {
          tmp.push({
            id: new Date().getTime() + '-' + index,
            src: path,
            uploadStatus: 0
          })
        })
        if (tmp.length > 12) {
          tmp = tmp.slice(0, 12)
        }
        _self.setData({
          storeImages: tmp
        })
      }
    })
  },
  uploadImg() {
    this.setData({
      uploadDisabled: true
    })
    wx.showLoading({
      title: '上传图片中',
    })

    //函数数组，每个函数的返回值是一个promise对象
    let promiseFuncArr = []
    const _self = this
    this.data.storeImages.forEach(item => {
      if (item.uploadStatus != 1) {
        let promiseTemp = function () {
          return new Promise((resolve, reject) => {
            wx.uploadFile({
              url: 'https://qdndcupload.ideatower.cn/apiAttachment/uploadAttachment?bucketName=qdndc',
              filePath: item.src,
              name: 'file',
              success: function (res) {
                var data = JSON.parse(res.data)
                if (data.code == 0) {
                  item.downloadPath = data.data[0].downloadPath
                }
                resolve(item)
              },
              fail: function () {
                reject(error)
              },
              complete: function () {
              }
            })
          })
        }
        promiseFuncArr.push(promiseTemp)
      }
    })
    _self.sequenceTasks(promiseFuncArr).then((result) => {
      //对返回的result数组进行处理
      if (promiseFuncArr.length == 0) {
        wx.hideLoading()
        this.showZanToast('请至少选择一张新的图片')
        return
      }
      result.forEach(item => {
        if (item.downloadPath) {
          item.uploadStatus = 1
        } else {
          item.uploadStatus = -1
        }
      })
      _self.data.storeImages.forEach(item => {
        const findObj = result.find(o => o.id == item.id)
        if (findObj) {
          item = Object.assign({}, item, findObj)
        }
      })
      _self.setData({
        storeImages: _self.data.storeImages,
        uploadDisabled: false
      })
      
      wx.hideLoading()
    })
  },
  bindImgLongTab(e) {
    let index = e.currentTarget.id.substring(3)
    const img = this.data.storeImages[parseInt(index)]
    if (img.uploadStatus == -1) {
      this.setData({
        moreImgOption: [{
          name: '删除该图片'
        }, {
          name: '重新上传'
        }]
      })
    } else {
      this.setData({
        moreImgOption: [{
          name: '删除该图片'
        }]
      })
    }

    this.setData({
      selectImg: img,
      showMoreImgOption: true
    })
  },
  handleZanActionsheetClick({ componentId, index }) {
    if (this.data.selectImg) {
      const t1 = this.data.storeImages
      if (index == 0) {
        // 删除
        const findIndex1 = t1.findIndex(o => o.id == this.data.selectImg.id)
        if (findIndex1 > -1) {
          t1.splice(findIndex1, 1)
          this.setData({
            storeImages: t1
          })
        }
      } else {
        // 重新上传
        wx.showLoading({
          title: '上传图片中',
        })
        const obj = t1.find(o => o.id == this.data.selectImg.id)
        if (obj) {
          const _self = this
          wx.uploadFile({
            url: 'https://qdndcupload.ideatower.cn/apiAttachment/uploadAttachment?bucketName=qdndc',
            filePath: obj.src,
            name: 'file',
            success: function (res) {
              var data = JSON.parse(res.data)
              if (data.code == 0) {
                obj.downloadPath = data.data[0].downloadPath
              }
            },
            fail: function () {
            },
            complete: function () {
              t1.forEach(item => {
                if (item.id == obj.id) {
                  if (obj.downloadPath) {
                    item.uploadStatus = 1
                    item.downloadPath = obj.downloadPath
                  } else {
                    item.uploadStatus = -1
                  }

                }
              })
              _self.setData({
                storeImages: t1,
              })
              wx.hideLoading()
            }
          })
        }
      }
      this.setData({
        showMoreImgOption: false
      })
    }
  },
  handleZanActionsheetCancel() {
    this.setData({
      showMoreImgOption: false
    })
  },
  //顺序处理函数
  sequenceTasks(tasks) {
    //记录返回值
    function recordValue(results, value) {
      results.push(value)
      return results
    }
    let pushValue = recordValue.bind(null, [])
    return tasks.reduce(function (promise, task) {
      return promise.then(task).then(pushValue)
    }, Promise.resolve())
  }
}))